// 超高性能懒加载指令 - 终极优化版本
export default {
  mounted(el, binding) {
    // 检查是否支持 Intersection Observer
    if (!window.IntersectionObserver) {
      // 降级处理：直接加载图片
      el.src = binding.value;
      return;
    }

    // 设置初始状态
    el.classList.add('lazy');
    el.style.opacity = '0';
    el.style.transition = 'opacity 0.15s ease-in-out'; // 更快的过渡

    // 使用更小的占位符
    if (!el.src) {
      el.src = '';
    }

    // 使用 requestIdleCallback 优化加载时机
    let loadTimeout;
    const loadImage = () => {
      if (loadTimeout) {
        clearTimeout(loadTimeout);
      }

      if ('requestIdleCallback' in window) {
        requestIdleCallback(() => {
          el.src = binding.value;
          el.classList.remove('lazy');
          el.classList.add('loaded');
          el.onload = () => {
            el.style.opacity = '1';
          };
        }, { timeout: 100 });
      } else {
        loadTimeout = setTimeout(() => {
          el.src = binding.value;
          el.classList.remove('lazy');
          el.classList.add('loaded');
          el.onload = () => {
            el.style.opacity = '1';
          };
        }, 25); // 更短的延迟
      }
    };

    // 创建观察器
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          loadImage();
          observer.unobserve(entry.target);
        }
      });
    }, {
      rootMargin: '150px 0px', // 更大的预加载距离
      threshold: 0.001 // 更早触发
    });

    // 开始观察
    observer.observe(el);

    // 保存observer引用以便清理
    el._observer = observer;
  },

  unmounted(el) {
    // 清理observer
    if (el._observer) {
      el._observer.disconnect();
    }
  }
};
